package org.budo.mail.javax.session.builder;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;

/**
 * @author lmw
 */
public class SmtpSessionBuilder {
    private Boolean debug;

    private String password;

    private String username;

    private Integer port;

    private String host;

    public SmtpSessionBuilder setHostPort(String host, Integer port) {
        this.host = host;
        this.port = port;

        return this;
    }

    public SmtpSessionBuilder setUsernamePassword(String username, String password) {
        this.username = username;
        this.password = password;

        return this;
    }

    public SmtpSessionBuilder setDebug(Boolean debug) {
        this.debug = debug;

        return this;
    }

    public Session toSession() {
        Properties properties = new Properties();

        // 表示SMTP发送邮件，需要进行身份验证
        properties.put("mail.smtp.auth", true);
        properties.put("mail.smtp.host", this.host);
        properties.put("mail.smtp.port", this.port);

        Authenticator authenticator = new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        };

        Session session = Session.getInstance(properties, authenticator);

        session.setDebug(this.debug);

        return session;
    }
}